#coding=utf-8
from django.core.urlresolvers import reverse
from django.shortcuts import (get_object_or_404, redirect, render,
                              render_to_response)
from django.contrib.auth.models import User
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.views.generic.edit import (CreateView, DeleteView, FormView,
                                       UpdateView)
from main import models,logic,forms
from django.contrib import auth
from django.views.decorators.csrf import csrf_exempt

from django.http import HttpResponse
from django.db import transaction
import datetime
import logging
import json 
from django.db.models import Count

logger = logging.getLogger('main')
# Create your views here.
def index(request):
    user = request.user
    if user and user.is_active:
        return render(request, 'main/index.html')
    else:
        return render(request, 'login/login.html')
 

def main_index(request):
    user = request.user
    if not (user and user.is_active):
        return render_to_response('login/login.html', {})
    
    return render(request,'main/index.html', {})

 
def tab(request):
    return render(request, 'main/tab.html')


def main_default(request):
    return render(request, 'main/main_default.html')


def main_defaultlist(request):
    return render(request, 'main/main_defaultlist.html')

def main_defaultedit(request):
    return render(request, 'main/main_defaultedit.html')

 
class MainDefaultListView(ListView):
    model = models.menu
    template_name = 'main/main_defaultlist1.html'

    def get_context_data(self, **kwargs):
        context = super(MainDefaultListView, self).get_context_data(**kwargs)
        user_id=self.request.user.pk
        print self.request.GET.get("KEYWORD")
        userinfo = models.user.objects.get(user_id=user_id)
       
        role_id = userinfo.role_id
        context['sub_item'] = models.subitem.objects.filter(role_id=role_id)
        context['menu_dict'] = models.menu.objects.all()
         
        logger.info("muen list struct objects all")
        return context

class TemplateVisitCreateView(UpdateView):
    model = models.TemplateText
    form_class = forms.TemplateTextUpdateForm
    template_name = 'assist/template_textedit.html'

    def get_success_url(self):
        # add admin log
        return reverse('template-visit-update',args=[self.kwargs['pk']])

    def get_initial(self):
        user_id = self.request.user.pk
        userName=self.request.user
        user=self.request.user
        logger.info ("template create paramer username %s, user_id %s .",userName,user_id)
        return { 'user': user, 'username':userName,'user_id':user_id}
    

    
class NewsManageListView(ListView):
    model = models.News
    template_name = 'main/news/news_manage_list.html'

    def get_context_data(self, **kwargs):
        context = super(NewsManageListView, self).get_context_data(**kwargs) 
            #页码数
        pagenum = self.request.GET.get("pagenum")
          #每页数据量
        pagecount = self.request.GET.get("pagecount")
        name = self.request.GET.get("name")
        
        news_list = models.News.objects.all()
        if name :
            news_list = news_list.filter(title__contains=name)
        news_list = news_list.order_by("-createDate")
        news_list,page = logic.list_to_pagelist(news_list,pagenum,pagecount)
        
        context['news_list'] = news_list
        context['page'] = page
        context['name'] = name
        return context


class NewsRecordCreateView(FormView):
    model = models.News
    form_class = forms.NewsRecordCreateForm
    template_name = 'main/news/news_info_add.html'

    def get_success_url(self):
        # add admin log
        return  HttpResponse("we")

    def get_initial(self):
        user_id = self.request.user.pk
        userName=self.request.user
        user=self.request.user
        logger.info ("news-record-create-view paramer username %s, user_id %s .",userName,user_id)
        return {'username':userName,'user_id':user_id}
  

@csrf_exempt
def news_info_save(request):
    logger.info ("news-info-save")
    try:
        id = request.POST.get("id")
        user=request.user
        user_id = user.id
        username = user.first_name
        title = request.POST.get("title")
        sort = request.POST.get("sort")
        desc = request.POST.get("desc")
        content = request.POST.get("content")
        news = models.News()
        if id:
            news = models.News.objects.get(id=id)
        if user_id:
            news.user_id=int(user_id)
        news.username=username
        news.title=title
        if sort:
            news.sort=int(sort)
        news.desc=desc
        news.content=content
        
        if request.FILES.has_key('img'):
            print request.FILES["img"]
            news.img = request.FILES["img"]
        news.save()
        return HttpResponse('{"result":"success"}')
        
    except Exception as e:
        logger.info("%s",e)
        return HttpResponse('{"result":"error"}')
 
   
class NewsRecordUpdateView(UpdateView):
    model = models.News
    form_class = forms.NewsRecordUpdateForm
    template_name = 'main/news/news_info_add.html'

    def get_success_url(self):
        # add admin log
        return  HttpResponse("we")

    def get_initial(self):
        user_id = self.request.user.pk
        userName=self.request.user
        user=self.request.user
        logger.info ("news-record-create-view paramer username %s, user_id %s .",userName,user_id)
        return {'username':userName,'user_id':user_id}
  
  
class NewsRecordDetailView(ListView):
    model = models.News
    template_name = 'main/news/news_detail.html'

    def get_context_data(self, **kwargs):
        context = super(NewsRecordDetailView, self).get_context_data(**kwargs) 
        news_id = self.kwargs['pk']
        
        news = models.News.objects.get(id=news_id)
        
        context['news'] = news
        return context
    

@csrf_exempt
def news_message_status_change(request):
    logger.info ("news-message-status-change")
    try:
        news_ids = request.POST.get("news_ids")
        status = request.POST.get("status")
        news_list = news_ids.split(',')
        models.News.objects.filter(id__in=news_list).update(status=status)
        
        return HttpResponse('{"result":"success"}')
        
    except Exception as e:
        logger.info("%s",e)
        return HttpResponse('{"result":"error"}')
    
class CoopertionManageListView(ListView):
    model = models.CoopertionPartner
    template_name = 'main/coopertion/coopertion_manage_list.html'

    def get_context_data(self, **kwargs):
        context = super(CoopertionManageListView, self).get_context_data(**kwargs) 
            #页码数
        pagenum = self.request.GET.get("pagenum")
          #每页数据量
        pagecount = self.request.GET.get("pagecount")
        name = self.request.GET.get("name")
        
        cooper_list = models.CoopertionPartner.objects.all()
        if name :
            cooper_list = cooper_list.filter(name__contains=name)
        cooper_list = cooper_list.order_by("-createDate")
        cooper_list,page = logic.list_to_pagelist(cooper_list,pagenum,pagecount)
        
        context['cooper_list'] = cooper_list
        context['page'] = page
        context['name'] = name
        return context


class CoopertionRecordCreateView(FormView):
    model = models.CoopertionPartner
    form_class = forms.CoopertionRecordCreateForm
    template_name = 'main/coopertion/coopertion_info_add.html'

    def get_success_url(self):
        # add admin log
        return  HttpResponse("we")

    def get_initial(self):
        user_id = self.request.user.pk
        userName=self.request.user
        user=self.request.user
        logger.info ("coopertion-record-create-view paramer username %s, user_id %s .",userName,user_id)
        return {'username':userName,'user_id':user_id}
  
  
@csrf_exempt
def coopertion_info_save(request):
    logger.info ("coopertion-info-save")
    try:
        id = request.POST.get("id")
        user=request.user
        user_id = user.id
        username = user.first_name
        name = request.POST.get("name")
        sort = request.POST.get("sort")
        desc = request.POST.get("desc")
        href = request.POST.get("href")
        coopertion = models.CoopertionPartner()
        if id:
            coopertion = models.CoopertionPartner.objects.get(id=id)
        if user_id:
            coopertion.user_id=int(user_id)
        coopertion.username=username
        coopertion.name=name
        if sort:
            coopertion.sort=int(sort)
        coopertion.desc=desc
        coopertion.href=href
        
        if request.FILES.has_key('img'):
            print request.FILES["img"]
            coopertion.img = request.FILES["img"]
        coopertion.save()
        return HttpResponse('{"result":"success"}')
        
    except Exception as e:
        logger.info("%s",e)
        return HttpResponse('{"result":"error"}')


class CoopertionRecordUpdateView(UpdateView):
    model = models.CoopertionPartner
    form_class = forms.CoopertionRecordUpdateForm
    template_name = 'main/coopertion/coopertion_info_add.html'

    def get_success_url(self):
        # add admin log
        return  HttpResponse("we")

    def get_initial(self):
        user_id = self.request.user.pk
        userName=self.request.user
        user=self.request.user
        logger.info ("coopertion-record-create-view paramer username %s, user_id %s .",userName,user_id)
        return {'username':userName,'user_id':user_id}
  
class CoopertionRecordDetailView(ListView):
    model = models.CoopertionPartner
    template_name = 'main/coopertion/coopertion_detail.html'

    def get_context_data(self, **kwargs):
        context = super(CoopertionRecordDetailView, self).get_context_data(**kwargs) 
        coopertion_id = self.kwargs['pk']
        
        coopertion = models.CoopertionPartner.objects.get(id=coopertion_id)
        
        context['coopertion'] = coopertion
        return context
    
    
@csrf_exempt
def coopertion_message_status_change(request):
    logger.info ("coopertion-message-status-change")
    try:
        coopertion_ids = request.POST.get("coopertion_ids")
        status = request.POST.get("status")
        coopertion_list = coopertion_ids.split(',')
        models.CoopertionPartner.objects.filter(id__in=coopertion_list).update(status=status)
        
        return HttpResponse('{"result":"success"}')
        
    except Exception as e:
        logger.info("%s",e)
        return HttpResponse('{"result":"error"}')
    
    
 
class WebImgManageListView(ListView):
    model = models.WebVisitImg
    template_name = 'main/webimg/webimg_manage_list.html'

    def get_context_data(self, **kwargs):
        context = super(WebImgManageListView, self).get_context_data(**kwargs) 
      
        webimg_list = models.WebVisitImg.objects.filter(status='1')
        webimg_list = webimg_list.values('meansure','type','desc').annotate(num=Count('id'))
        
        webimg_temp = models.WebVisitImg()
        for webimg in webimg_list:
            webimg_temp.type = webimg["type"]
            webimg["typename"] = webimg_temp.get_type_display()
        context['webimg_list'] = webimg_list
        return context
    
class WebimgRecordUpdateView(UpdateView):
    model = models.WebVisitImg
    form_class = forms.WebimgRecordUpdateForm
    template_name = 'main/webimg/webimg_info_add.html'

    def get_success_url(self):
        # add admin log
        return  HttpResponse("we")

    def get_initial(self):
        user_id = self.request.user.pk
        userName=self.request.user
        user=self.request.user
        logger.info ("webimg-record-update-view paramer username %s, user_id %s .",userName,user_id)
        return {'username':userName,'user_id':user_id}
  
  
@csrf_exempt
def webimg_info_save(request):
    logger.info ("web-img-info-save")
    try:
        id = request.POST.get("id")
        name = request.POST.get("name")
        href = request.POST.get("href")
        sort = request.POST.get("sort",0)
        user=request.user
        user_id = user.id
        username = user.first_name

        webimg = models.WebVisitImg.objects.get(id=id)
        webimg.user_id=int(user_id)
        webimg.username=username
        webimg.name=name
        webimg.href=href
        webimg.sort=sort
        
        if request.FILES.has_key('img'):
            print request.FILES["img"]
            webimg.img = request.FILES["img"]
        webimg.save()
        return HttpResponse('{"result":"success"}')
        
    except Exception as e:
        logger.info("%s",e)
        return HttpResponse('{"result":"error"}')
   
class WebConfigFormView(FormView):
    model = models.WebConfig
    form_class = forms.WebConfigCreateForm
    template_name = 'main/config/web_config_info_update.html'

    def get_context_data(self, **kwargs):
        context = super(WebConfigFormView, self).get_context_data(**kwargs) 
        logger.info ("web config info update")
        webconfig = models.WebConfig.objects.get(id=1)
        context['webconfig'] = webconfig
        return context

@csrf_exempt
def web_config_page_save(request):
    logger.info ("web-config-page-save")
    try:
        id = request.POST.get("id")
        title = request.POST.get("title")
        keywords = request.POST.get("keywords")
        description = request.POST.get("description")
        copyright = request.POST.get("copyright")
        icp = request.POST.get("icp")
        address = request.POST.get("address")
        email = request.POST.get("email")
        phone = request.POST.get("phone")
        service1name = request.POST.get("service1name")
        service1phone = request.POST.get("service1phone")
        service2name = request.POST.get("service2name")
        service2phone = request.POST.get("service2phone")
        service3name = request.POST.get("service3name")
        service3phone = request.POST.get("service3phone") 
        
        webconfig = models.WebConfig.objects.get(id=id)
        webconfig.title = title
        webconfig.keywords = keywords
        webconfig.description = description
        webconfig.copyright = copyright
        webconfig.icp = icp
        webconfig.address = address
        webconfig.email = email
        webconfig.phone = phone
        webconfig.service1name = service1name
        webconfig.service1phone = service1phone
        webconfig.service2name = service2name
        webconfig.service2phone = service2phone
        webconfig.service3name = service3name
        webconfig.service3phone = service3phone
        
        
        
        webconfig.save()
        return HttpResponse('{"result":"success"}')
        
    except Exception as e:
        logger.info("%s",e)
        return HttpResponse('{"result":"error"}')


class WebConfigUpdateView(ListView):
    model = models.WebConfig
    template_name = 'main/config/web_config_batchfile.html'

    def get_context_data(self, **kwargs):
        context = super(WebConfigUpdateView, self).get_context_data(**kwargs)
         
        config_id = self.kwargs['param1']
        type = self.kwargs['param2']
        
        context["config_id"] = config_id
        context["type"] = type
        
        logger.info("web config img upload page")
        return context
  
  
@csrf_exempt
def web_config_fileupload_save(request):
    logger.info ("web config file upload save")
    try:
        config_id= request.POST.get("config_id")
        type= request.POST.get("type","")
         
        
        webconfig = models.WebConfig.objects.get(id=config_id)
        
        if type == "1":
            print config_id
            print type
            if request.FILES.has_key('fileurl'):
                print '23'
                webconfig.logoimg = request.FILES["fileurl"]
        elif type == '2':
            if request.FILES.has_key('fileurl'):
                webconfig.wechatimg = request.FILES["fileurl"]
        webconfig.save()
        return HttpResponse('{"result":"success"}')
        
    except Exception as e:
        logger.info("%s",e)
        return HttpResponse('{"result":"error"}')
    
    

class ChangePasswordFormView(ListView):
    model = User
    template_name = 'main/config/user_change_password.html'

    def get_context_data(self, **kwargs):
        context = super(ChangePasswordFormView, self).get_context_data(**kwargs)
          
        logger.info("change password form upload page")
        return context


@csrf_exempt
def change_passowrd_save(request):
    logger.info ("change password save ")
    newpassword = request.POST.get("newpassword")
    oldpassword = request.POST.get("oldpassword")
    name_dict = {}
    try:
        user = request.user
         
        user_validate = auth.authenticate(username=user.username,password=oldpassword)
        
        name_dict = {'result':'olderror'}
       
        if user_validate is not None:
            user_data = User.objects.get(id=user.id)
            user_data.set_password(newpassword)
            user_data.save()
            auth.logout(request)
            name_dict = {'result':'success'}
        
    except Exception as e:
        logger.info("%s",e)
        
    return HttpResponse(json.dumps(name_dict), content_type='application/json') 

  
class WebAdvImgUpdateView(FormView):
    model = models.WebVisitImg
    form_class = forms.WebAdvImgUpdateForm
    template_name = 'main/webimg/webimg_info_add.html'

    def get_context_data(self, **kwargs):
        context = super(WebAdvImgUpdateView, self).get_context_data(**kwargs)
        img_type = self.kwargs['param']
        imgvisit = models.WebVisitImg.objects.get(status='1',type=img_type)
        context['imgvisit'] = imgvisit
        logger.info("web adv img update ")
        return context
    
class WebAdvImgListView(ListView):
    model = models.WebVisitImg
    template_name = 'main/webimg/web_adv_img_list.html'

    def get_context_data(self, **kwargs):
        context = super(WebAdvImgListView, self).get_context_data(**kwargs)
         
        img_type = self.kwargs['param']
        img_list = models.WebVisitImg.objects.filter(status='1',type=img_type)
        
        
        context["img_list"] = img_list
        context["img_type"] = img_type
        
        logger.info("web adv img list view")
        return context   
    

class WebAdvImgByIdUpdateView(ListView):
    model = models.WebVisitImg
    template_name = 'main/webimg/webimg_info_mult_add.html'

    def get_context_data(self, **kwargs):
        context = super(WebAdvImgByIdUpdateView, self).get_context_data(**kwargs)
        img_id = self.kwargs['param']
        imgvisit = models.WebVisitImg.objects.get(id=img_id)
        context['imgvisit'] = imgvisit
        logger.info("web adv img update ")
        return context
    